/*
 * @Author: Liz.Zheng
 * @Date: 2021-10-11 11:19:37
 * @LastEditTime: 2022-06-01 14:19:55
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description:
 * @Motto: Write the code. Change the world.
 */
import { message, Modal, notification } from "ant-design-vue";
import defaultSetting from "./defaultSetting";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { createVNode } from "vue";
import store from "../../store";
import request from "./request";

const utils = {
  // 图片上传的地址
  imgAction: request.BASE_URL + "/public/system/uploadImage",
  fileAction: request.BASE_URL + "/public/system/uploadFile",
  // 数字验证正则
  numberReg: /^\d+(\.\d+)?$/,

  staticPath:
    (defaultSetting.requestDomain || "http://127.0.0.1") +
    "/public_web/static/",

  /**
   * @description: 数组合并并去重
   * @param {Array} arr1
   * @param {Array} arr2
   * @return {Array} arr
   */
  combineArr: (arr1, arr2) => {
    let arr = [...arr1, ...arr2];
    return Array.from(new Set(arr));
  },
  /**
   * @description: 楼宇信息转换为treeData
   * @param {Array}data 接口返回
   * @return {Array}list treeData
   */
  transformVilliageData: (data) => {
    let list = [];
    if (data.length) {
      list = data.map((item) => {
        let vItem = {};
        vItem.key = `parent_${item.id}`;
        vItem.value = `parent_${item.id}`;
        vItem.title = item.name;
        vItem.children = item.buildList.map((item2) => {
          let bItem = {};
          bItem.key = item2.id;
          bItem.value = item2.id;
          bItem.title = item2.build_name;
          return bItem;
        });
        return vItem;
      });
    }
    return list;
  },

  /**
   * @description: 楼宇选中与提交字段互转
   * @param {Array | Object}
   * @return {Array | Object}
   */
  transformBuildData: (data) => {
    if (data.ids) {
      // {ids,names} => {label,value}
      return data.ids.map((id) => {
        return {
          value: id,
          label: data.names[id],
        };
      });
    } else {
      // {label,value} => {ids,names}
      let ids = [];
      let names = {};
      if (data.length) {
        data.forEach((item) => {
          ids.push(item.value);
          names[item.value] = item.label || "";
        });
      }
      return { ids, names };
    }
  },
  /**
   * @description: 根据id获取部门内容
   * @param {String | Number} id 部门id
   * @param {Array} list 部门列表
   * @return {Object} 当前部门
   */
  getDepartmentById: (id, list) => {
    if (!id || !list || !list.length) {
      return;
    }
    for (let item of list) {
      if (item.key == id) {
        return item;
      }
      if (item.children && item.children.length) {
        const current = utils.getDepartmentById(id, item.children);
        if (current) {
          return current;
        }
      }
    }
  },
  /**
   * @description: 根据部门名称获取部门内容
   * @param {String | Number} id 部门id
   * @param {Array} list 部门列表
   * @param {Array} result 符合条件的列表
   */
  getDepartmentByName: (name, list, result) => {
    if (!name || !list || !list.length) {
      return;
    }
    for (let item of list) {
      if (item.title.indexOf(name) > -1) {
        result.push(item);
      }
      if (item.children && item.children.length) {
        utils.getDepartmentByName(name, item.children, result);
      }
    }
  },

  /**
   * @description: 确认弹框（删除确认） 重写是为了多语言
   * @param {*} 同ant design api
   */
  modalConfirm: ({
    title = "提示",
    content = {},
    centered = true,
    onOk,
    onCancel,
    okType = "primary",
  }) => {
    Modal.confirm({
      title: () => title,
      content: () => content,
      okText: () => "确定",
      icon: () => createVNode(ExclamationCircleOutlined),
      okType,
      cancelText: () => "取消",
      centered,
      onOk() {
        onOk && onOk();
      },
      onCancel() {
        onCancel && onCancel();
      },
    });
  },

  /**
   * @description: 表单验证为数字
   * @param {Object} rules 规则
   * @param {*} value 值
   */
  numberValidator: async (rules, value) => {
    // console.log("rules,value", rules, value);
    const valueNotEmpty = value || value == "0" ? true : false;
    if (rules.required && !valueNotEmpty) {
      return Promise.reject("必填项");
    }
    if (valueNotEmpty && !utils.numberReg.test(value)) {
      return Promise.reject("请输入数字");
    }
    return Promise.resolve();
  },

  /**
   * @description: 获取图片真实宽高
   * @param {String} url 图片地址
   * @param {Object} size 宽高
   */
  getImageSize: (url) => {
    return new Promise((resolve) => {
      const image = new Image();
      image.src = url;
      image.onload = function () {
        // console.log("图片原始高度", image.height);
        // console.log("图片原始宽度", image.width);
        resolve(image);
      };
    });
  },

  /**
   * @description: 动态获取keep-alive数组
   * @param {Array} list 路由表
   * @param {Array} result
   */
  getKeepAliveRoutes: (list, result) => {
    for (let item of list) {
      if (item.meta && item.meta.keepAlive === true) {
        result.push(item.name);
      }
      if (item.children && item.children.length) {
        utils.getKeepAliveRoutes(item.children, result);
      }
    }
  },

  /**
   * @description: 根据id获取当前菜单
   * @param {Array} list 路由表
   *  @param {Array} id 菜单id
   * @param {Object} current
   */
  getCurrentMenuById: (list, id) => {
    for (let menu of list) {
      if (menu.id == id) {
        return menu;
      }
      if (menu.children && menu.children.length) {
        const item = utils.getCurrentMenuById(menu.children, id);
        if (item) {
          return item;
        }
      }
    }
  },

  /**
   * @description: 复制内容到剪切板
   * @param {String} content
   */
  copyText: (content) => {
    let ele = document.createElement("input"); //创建一个input标签
    ele.setAttribute("value", content); // 设置改input的value值
    document.body.appendChild(ele); // 将input添加到body
    ele.select(); // 获取input的文本内容
    document.execCommand("copy"); // 执行copy指令
    document.body.removeChild(ele); // 删除input标签
    notification.success({ message: "复制成功！", duration: 1 });
  },

  /**
   * @description: 获取省市区县等信息
   * @param {Number} level 当前等级
   * @param {Array} optionList 返回的列表
   * @param {Object} extra 其他信息： id 请求id ; leafLevel: 叶子节点等级
   */
  getAreaOptions: (level, optionList, extra = { id: "", leafLevel: 5 }) => {
    return new Promise((resolve) => {
      let requestUrl = "";
      let requestParams = {};
      switch (level) {
        case 1:
          // 省
          requestUrl = "/district/province_list";
          break;
        case 2:
          // 市
          requestUrl = "/district/city_list";
          requestParams = { province_id: extra.id };
          break;
        case 3:
          // 区
          requestUrl = "/district/district_list";
          requestParams = { city_id: extra.id };
          break;
        case 4:
          // 街道/乡
          requestUrl = "/district/street_list";
          requestParams = { district_id: extra.id };
          break;
        case 5:
          // 社区/村
          requestUrl = "/district/community_list";
          requestParams = { street_id: extra.id };
          break;
        default:
          requestUrl = "";
          break;
      }
      if (requestUrl) {
        let leafLevel = extra.leafLevel || 5;
        request.get("/public", requestUrl, requestParams).then((res) => {
          if (res.list) {
            optionList = res.list.map((item) => ({
              value: item.area_code,
              label: item.name,
              level,
              isLeaf: level == leafLevel,
            }));
            resolve(optionList);
          }
        });
      }
    });
  },
  /**
   * @description: 整数前面补0
   * @param {Number} num 待处理的整数
   * @param {Number} len 需要的长度
   */
  prefixInteger: (num, len) => {
    return (Array(len).join("0") + num).slice(-len);
  },

  /**
   * @description: 验证页面元素是否有权限操作或查看
   * @param {Array} action 待验证的action
   * @return {Boolean}
   */
  actionPermission: (action) => {
    if (!action || !Array.isArray(action) || action.length < 2) {
      notification.error({
        message: "错误",
        description: "v-action格式错误",
      });
    }
    const actions = store.getters.currentActions;
    if (actions) {
      for (let key in actions) {
        if (key == action[0]) {
          if (actions[key].includes(action[1])) {
            return true;
          }
        }
      }
    }
    return false;
  },

  /**
   * @description: 获取缓存姓名
   * @param {String} name
   */
  getStorageName: (name) => {
    return `${defaultSetting.from}_${defaultSetting.name}_${name}`;
  },

  /**
   * @description: 设置存储
   * @param {String}name 存储变量名
   * @param {*}info 存储内容
   * @param {Boolean} isCache 是否持久存储
   */
  setStorage: (name, info, isCache) => {
    const storageName = utils.getStorageName(name);
    if (isCache) {
      sessionStorage.setItem(storageName, info);
    } else {
      localStorage.setItem(storageName, info);
    }
  },
  /**
   * @description: 获取存储
   * @param {String}name 存储变量名
   * @param {Boolean} isCache 是否持久存储
   * @return {*} info 存储的内容
   */
  getStorage: (name, isCache) => {
    const storageName = utils.getStorageName(name);
    let info = null;
    if (isCache) {
      info = sessionStorage.getItem(storageName);
    } else {
      info = localStorage.getItem(storageName);
    }
    return info;
  },
  /**
   * @description: 移除存储
   * @param {String}name 存储变量名
   * @param {Boolean} isCache 是否持久存储
   */
  removeStorage: (name, isCache) => {
    const storageName = utils.getStorageName(name);
    if (isCache) {
      sessionStorage.removeItem(storageName);
    } else {
      localStorage.removeItem(storageName);
    }
  },
  /**
   * @description: 清空存储
   * @param {Boolean} isCache 是否是清空持久存储
   */
  clearStorage: (isCache) => {
    if (isCache) {
      sessionStorage.clear();
    } else {
      localStorage.clear();
    }
  },

  /**
   * @description: 打印数据
   * @param {*} msg 可选 打印的变量
   * @param {String}title  可选 打印的title
   */
  consoleInfo: (msg = "", title = "") => {
    console.group(
      `%c${new Date().toLocaleTimeString()} 【子应用-${defaultSetting.name}】`,
      `color:#426666;font-weight: bold;`
    );
    console.log(`${title} -- `, msg);
    console.groupEnd();
  },

  /**
   * @description: 判断当前是否是手机端
   */
  isMobile: () => {
    const mobile = navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    );
    return mobile ? true : false;
  },

  // 是否是开发环境
  isEnv: () => {
    if (process.env.NODE_ENV === "development") {
      return true;
    }
    return false;
  },
  /**
   * @description: 设置页面标题
   * @param {String} title
   */
  setDocumentTitle: (title) => {
    document.title = `${title}`;
    const ua = navigator.userAgent;
    // eslint-disable-next-line no-useless-escape
    const regex = /\bMicroMessenger\/([\d\.]+)/;
    if (regex.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
      const i = document.createElement("iframe");
      i.src = "/favicon.ico";
      i.style.display = "none";
      i.onload = function () {
        setTimeout(function () {
          i.remove();
        }, 9);
      };
      document.body.appendChild(i);
    }
  },

  /**
   * @description: 表单验证为手机号
   */
  phoneValidator: async (rule, value) => {
    if (!value) {
      if (rule.required) {
        return Promise.reject("必填项");
      }
      return Promise.resolve();
    }
    if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) {
      return Promise.reject("请输入正确的手机号码");
    }
    return Promise.resolve();
  },

  /**
   * @description: 为公共组件提供的请求方法
   */
  commonRequest: (emitObj) => {
    const { params, success, fail } = emitObj;
    const { method, server, url, extra = {} } = params;
    request[method](server, url, extra)
      .then((res) => success(res))
      .catch((err) => fail(err));
  },
};
export default utils;
